package cn.ulc.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class CommonUtil {

  public static String encodeTicket(String scene){
    return encodeTicket(scene,2*60*1000l);
  }

  public static String encodeTicket(String scene,Long millis){
    if(StrUtil.isBlank(scene)) return null;
    scene += '-' + millis;
    return Base64.encode(scene);
  }

  public static Map<String,Object> decodeTicket(String scene){
    if(StrUtil.isBlank(scene)) return null;
    Map<String,Object> map = new HashMap<>();
    String query = Base64.decodeStr(scene);
    if(StrUtil.isNotBlank(query)){
      String[] qs = query.split("-");
      if(qs.length == 3){
        map.put("id", Convert.toLong(qs[1],0l));
        map.put("expired",Convert.toDate(qs[2]));
        return map;
      }
    }
    return null;
  }
  private static String NUMBER_CHARS = "0123456789";
  private static String LETTER_CHARS = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789";

  /**
   * 产生指定位数的随机数字
   *
   * @param length 长度
   * @return 随机数
   */
  public static String generateRandomNumberString(int length) {
    char[] charsArray = NUMBER_CHARS.toCharArray();
    Random random = new Random(System.currentTimeMillis());
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      sb.append(charsArray[random.nextInt(charsArray.length)]);
    }
    String text = sb.toString();
    return text;
  }

  /**
   * 产生指定位数的随机字符串(包含字母)
   *
   * @param length 长度
   * @return 随机数
   */
  public static String generateRandomChars(int length) {
    char[] charsArray = LETTER_CHARS.toCharArray();
    Random random = new Random(System.currentTimeMillis());
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      sb.append(charsArray[random.nextInt(charsArray.length)]);
    }
    return sb.toString();
  }

  /**
   * 生成唯一编码
   * @param letter 首字母
   * @param contain 必须包含的字符串
   * @return
   */
  public static String createNo(String letter, String contain){
    return createNo(letter,contain,13,null);
  }
  /**
   * 生成唯一编码
   * @param letter 首字母
   * @param contain 必须包含的字符串
   * @param length 编码长度
   * @param prevCode 同规则的上一个code
   * @return
   */
  public static String createNo(String letter, String contain, Integer length, String prevCode) {
    if (StrUtil.isBlank(contain)) contain = "";
    if (length == null) length = 13;
    String newCode = letter + contain;
    String num = "1";
    if (StrUtil.isNotBlank(prevCode)) {
      num = (Convert.toInt(prevCode.substring(newCode.length()), 0) + 1) + "";
    }
    Integer len = length - newCode.length() - num.length();
    if (len > 0) {
      for (int j = 0; j < len; j++) {
        newCode += "0";
      }
    }
    return newCode;
  }
}
